import axios from 'axios';
const request = axios.create();
import toFormData from './jsonToFormData';
import { isRef, isReactive, toRaw } from 'vue';

// 请求拦截
request.interceptors.request.use(
  config => {
    return config;
  },
  error => Promise.reject(error),
);

// 响应拦截
request.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    return Promise.reject(error);
  },
);

/**
 * POST 请求
 * @param {string} url 接口的地址
 * @param {Object} data 请求参数
 * @returns {Promise} 返回的内容中最少包含一个 code 码
 */
const POST = (url, data = {}) => {
  if (!url) return;
  if (isRef(data)) {
    data = data.value;
  } else if (isReactive(data)) {
    data = toRaw(data);
  }
  url = process.env.NODE_ENV === 'development' ? `/api${url}` : url;
  let formData = toFormData(data);
  return request({
    url: url,
    method: 'post',
    data: formData,
  });
};
const GET = (url, params = {}) => {
  if (!url) return;
  if (isRef(params)) {
    params = params.value;
  } else if (isReactive(params)) {
    params = toRaw(params);
  }
  url = process.env.NODE_ENV === 'development' ? `/api${url}` : url;
  return request({
    url: url,
    method: 'get',
    params,
  });
};

export { GET, POST, request };
